<?php
if (! defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' );
/**
 * 功能:上传图片文件
 * ===================================================================
 *
 * ===================================================================
 * 作者：李龙根
 * 时间:2015-8-6
 */
class ImageUpload extends CI_Controller{
	public $save_path;//储存路径
	public $type = array("jpg","gif","bmp","jpeg","png");//设置允许上传文件的类型
	public $resource;
	public function __construct($config=array()){
		if(count($config)>0)
		{
			foreach($config as $key => $value)
			{
				$this->$key = $value;
			}
		}
	}
	//获取文件后缀名函数
	public function fileext($filename)
	{
		return substr(strrchr($filename,"."),1);
	}
	//生成随机文件名函数
	public function random($length)
	{
		$hash = "CR-";
		$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
		$max = strlen($chars)-1;
		for($i = 0;$i<$length;$i++)
		{
			$hash.=$chars[mt_rand(0,$max)];
		}
		return $hash;
	}
	public function judgeType()
	{
		$this->createDir();
		if(!in_array(strtolower($this->fileext($this->resource['name'])),$this->type)){
			$text = implode(",",$this->type);
			echo "您只能上传一下类型文件:".$text."<br />";
			exit;
		}
	}
	public function createDir()
	{
		//echo $this->save_path;
		if(!file_exists($this->save_path))
		{
			//echo "11111";
			mkdir($this->save_path,0777,true);
		}
	}
	public function upload()
	{
		$this->judgeType();
		$filename = explode(".",$this->resource['name']);
		do{
			$filename[0] = $this->random(10);//设置随机数长度
			$name = implode(".",$filename);
			$uploadfile=$this->save_path.$name;
		}while(file_exists($uploadfile));
		if(is_uploaded_file($this->resource['tmp_name']))
		{
			if(move_uploaded_file($this->resource['tmp_name'],$uploadfile))
			{
				return $uploadfile;	
			}
		}
		else{
			echo "上传失败";
		}
	}
}